package com.lvcoding.auth2.auth.shizhan.security;

import com.lvcoding.auth2.auth.shizhan.entity.SysUser;
import com.lvcoding.auth2.auth.shizhan.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author wuyanshen
 */
@RequiredArgsConstructor
@Component
public class DefaultUserDetailsService implements CustomUserDetailService {

    private final SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.queryByName(username);

        if (sysUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        List<String> roles = sysUserService.queryRoleByUserId(sysUser.getId());

        Set<SimpleGrantedAuthority> collect = roles.stream()
                .map(name -> "ROLE_" + name)
                .map(SimpleGrantedAuthority::new).collect(Collectors.toSet());

        return new User(sysUser.getUsername(), sysUser.getPassword(), true, true, true, true, collect);
    }

}
